<?php
require_once "core/init.php";

$user = new User();

if (!$user->isLoggedIn()) {
	Riderect::to('index.php');
}

if (input::exists()) {
	if (Token::check(Input::get('token'))) {
		
		$validate = new Validation();
		$validation = $validate->check($_POST, array(
		'name' => array(
				'required' => true,
				'min' => 2,
				'max' => 50
			)
		));

		if ($validation->passed()) {
			
			try {
			
				$user->update(array(
					
					'name' => Input::get('name'),
					'username' => Input::get('username')	

				));
				Session::flash('home', 'Your details have been updated.');
				Redirect::to('index.php');
			} catch (Exception $e) {
			
				die($e->getMessage());	
			
			}
		
		}else {
			foreach ($validation->errors() as $error) {
				echo $error, '<Br/>';
			}
		}
	}	
}
?>

<form action="" method="post">
	<div class="field">
		<label for="name">Name</label>
		<input type="text" name="name" value="<?php echo escape($user->data()->name); ?>">
	</div>
	<div class="field">
		<label for="name">Username</label>
		<input type="text" name="username" value="<?php echo escape($user->data()->username); ?>">
	</div>
	<div class="field">
		<input type="submit" value="update">
		<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
	</div>
</form>	